package com.lagou.task.Filter;

import com.lagou.task.entity.Admin;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest servletRequest = (HttpServletRequest) req;
        // 获取登陆对象
        Admin admin = (Admin) servletRequest.getSession().getAttribute("admin");
        // 获取请求路径
        String servletPath = servletRequest.getServletPath();
        // 查看是否存在cookie
        boolean adminCookie = false;
        boolean passwordCookie = false;
        Cookie[] cookies = servletRequest.getCookies();
        for (Cookie cookie:cookies){
            if (cookie.getName().equals("adminName")){
                adminCookie = true;
            }else if (cookie.getName().equals("password")){
                passwordCookie = true;
            }
        }

        // 首先判断是否存在cookie
        if (adminCookie && passwordCookie){
            chain.doFilter(req, resp);
        }else {
            // 若不满足，则拦截
            if (admin == null && !servletPath.contains("login")){
                RequestDispatcher requestDispatcher = servletRequest.getRequestDispatcher("login.jsp");
                requestDispatcher.forward(req, resp);
            }
            // 若满足，则放行
            else {
                chain.doFilter(req, resp);
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
